package com.Xht.www.servlet;

//后端响应用户收藏商家的请求

import com.Xht.www.dao.UserFavoritesDAO;
import com.Xht.www.po.UserFavoritesPO;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet("/user-favorites")
public class UserFavoritesServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();

        try {
            String userIdParam = request.getParameter("userId");
            if (userIdParam == null || userIdParam.isEmpty()) {
                out.write("{\"success\": false, \"message\": \"用户ID不能为空\", \"data\": []}");
                return;
            }

            int userId = Integer.parseInt(userIdParam);
            UserFavoritesDAO dao = new UserFavoritesDAO();
            List<UserFavoritesPO> favorites = dao.getUserFavoritesByUserId(userId);

            StringBuilder json = new StringBuilder();
            json.append("{\"success\": true, \"message\": \"获取成功\", \"data\": [");

            for (int i = 0; i < favorites.size(); i++) {
                UserFavoritesPO favorite = favorites.get(i);
                json.append("{");
                json.append("\"favoriteId\": ").append(favorite.getFavoriteId()).append(",");
                json.append("\"merchantName\": \"").append(escapeJson(favorite.getMerchantName())).append("\",");
                json.append("\"favoriteReason\": \"").append(escapeJson(favorite.getFavoriteReason())).append("\",");
                json.append("\"favoriteTime\": \"").append(favorite.getFavoriteTime()).append("\"");
                json.append("}");

                if (i < favorites.size() - 1) {
                    json.append(",");
                }
            }

            json.append("]}");
            out.write(json.toString());

        } catch (Exception e) {
            e.printStackTrace();
            out.write("{\"success\": false, \"message\": \"服务器内部错误\", \"data\": []}");
        }
    }



    private String escapeJson(String s) {
        if (s == null) return "";
        return s.replace("\\", "\\\\")
                .replace("\"", "\\\"")
                .replace("\n", "\\n")
                .replace("\r", "\\r")
                .replace("\t", "\\t");
    }
}
